import { mapState, mapGetters, mapMutations, mapActions, useStore } from 'vuex';
import { computed } from 'vue';

interface UseFactoryStoreProps {
  namespaced: string,
  gettersMethod?: string[],
  mutationsMethod?: string[],
  actionsMethod?: string[]
}

/**
 * @param {*} namespaced 模块名称
 * @param {*} gettersMethod getters方法名
 * @param {*} mutationsMethod  mutations方法名
 * @param {*} actionsMethod actions方法名
 */

export const useFactoryStore = ({
  namespaced = '',
  gettersMethod = [],
  mutationsMethod = [],
  actionsMethod = []
}: UseFactoryStoreProps) => {
  const store = useStore();
  if (namespaced === '') {
    return { store, mapState, mapGetters, mapMutations, mapActions };
  }

  // state
  const state = computed(() => store.state[namespaced].value);

  // mapGetters
  const getters = mapGetters(namespaced, gettersMethod);
  const getter = {};
  gettersMethod.forEach((key) => {
    getter[key] = computed(getters[key].bind({ $store: store }));
  });

  // mapMutations
  const mutations = mapMutations(namespaced, mutationsMethod);
  const mutation = {};
  mutationsMethod.forEach((key) => {
    mutation[key] = mutations[key].bind({ $store: store });
  });

  // mapActions
  const actions = mapActions(namespaced, actionsMethod);
  const action = {};
  actionsMethod.forEach((key) => {
    action[key] = actions[key].bind({ $store: store });
  });

  return {
    mapState,
    mapGetters,
    mapMutations,
    mapActions,
    state,
    getter,
    mutation,
    action
  }
}
